<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;

use App\Order;

use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_order;
use DB;

use App\Line;
use App\Agent;


class  BatchController extends Controller
{

    public function batchRenew(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        // 续费用户名
        if(!$request->has('batch-username') || empty($request->has('batch-username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = trim($request->input('batch-username'),',');

        //   续费日期类型
        if(!$request->has('batch-renew-date-type') || empty($request->has('batch-renew-date-type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $date_type = $request->input('batch-renew-date-type');


        //  单价
        if(!$request->has('renew_discount') || empty($request->has('renew_discount')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $discount = $request->input('renew_discount');

        //   学费时间
        if(!$request->has('batch-renew-date') || empty($request->has('batch-renew-date')))
        {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }
        $date = $request->input('batch-renew-date');


        //  续费价格
        if(!$request->has('batch-renew-price') || empty($request->has('batch-renew-price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('batch-renew-price');

        if($price <=0)
        {
            self::ShowError(ErrorDefine::INVALID_PRICE);
            return;
        }

        //  获取用户信息
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $manage = self::getTokenById($token);


        if(empty($manage))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $manage_id =  $manage[0]['manage_id'];


        //  判断余额是否充足
        if($manage[0]['balance'] < $price)
        {
            self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
            return;
        }

        $renew_time = 0;
        //   续费时间
        switch($date_type)
        {
            case '日': $renew_time = $date * 86400 *1;break;
            case '周': $renew_time = $date * 86400 *7;break;
            case '月': $renew_time = $date * 86400 *30;break;
        }

        $expired_at = 0;

        //  更新用户信息

        $username = explode(',',$username);
        foreach($username as $value)
        {

            $users = Rad_users::where('username',$value)->first();

            if(strtotime($users->expired_at) > time())
            {
                $expired_at =  strtotime($users->expired_at) + $renew_time;
            }else{
                $expired_at = time() + $renew_time;
            }
            $users->expired_at = date('Y-m-d H:i:s',$expired_at);
            $users->save();


            $time = date("d M Y H:i:s ",$expired_at);
            $radcheck =  Radcheck::where('username',$value)->where('attribute','Expiration')->first();
            $radcheck->value = $time;
            $radcheck->save();
            $money = $users->con_max * $date *  $discount;

            //  订单

            $order = [];
            $order['order_no'] = self::createUuid();
            $order['user_id'] =$manage_id ;
            $order['pay_channel'] =2;
            $order['connect_num'] = $users->con_max;
            $order['to_user'] = $users->user_id;
            $order['account_type'] = '付费';
            $order['balance'] = $manage[0]['balance']-$money;
            $order['date'] =$date;
            $order['price'] =$money;
            $order['created_at'] = date('Y-m-d H:i:s',time());
            $order['updated_at'] = date('Y-m-d H:i:s',time());

            $id = Rad_order::insertGetId($order);

            if($id)
            {
                $orders = Rad_order::find($id);
                $orders->status = 1;
                $orders->save();
            }
        }

        return self::ShowMessage();

    }


    public function batchAdd(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //  批量添加用户名
        if(!$request->has('batch-add-username') || empty($request->has('batch-add-username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = explode(',',$request->input('batch-add-username'));


        if(!$request->has('set-meal-type') || empty($request->has('set-meal-type')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $set_meal_type = $request->input('set-meal-type');

        //  检测用户是否在
        $_user  = Rad_users::whereIn('username',$username)->get()->toArray();

        $_check = Radcheck::whereIn('username',$username)->get()->toArray();


        if(!empty($_user) && !empty($_check))
        {
            self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
            return;
        }


        //   批量添加密码
        if(!$request->has('batch-password') && empty($request->input('batch-password')))
        {
            self::ShowError(ErrorDefine::ILLEGAL_PASSWORD);
            return;
        }
        $password = $request->input('batch-password');

        //  批量添加日期类型
        if(!$request->has('batch-add-date-type') && empty($request->input('batch-add-date-type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $date_type = $request->input('batch-add-date-type');


        //   批量开通连接数
        if(!$request->has('batch-connect-num') && empty($request->input('batch-connect-num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $connect_num = $request->input('batch-connect-num');

        if($connect_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }

        //   开户人的 token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //  批量添加的日期
        if(!$request->has('batch-add-date') && empty($request->input('batch-add-date')))
        {
            self::ShowError(ErrorDefine::DATE_NOT_EXIST);
            return;
        }
        $add_date= $request->input('batch-add-date');

        if($add_date<=0) {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }


        //   开通账号数量
        if(!$request->has('batch-add-num') && empty($request->input('batch-add-num')) )
        {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }
        $batch_add_num = $request->input('batch-add-num');


        // 批量添加的价格
        if(!$request->has('batch-add-price') && empty($request->input('batch-add-price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('batch-add-price');



        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id =  $user[0]['manage_id'];

        if( $user[0]['balance'] < $price)
        {
            return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
        }

        switch ($date_type) {
            case '日':
                $expired_at = time() + 86400 * $add_date * 1;
                break;
            case '周':
                $expired_at = time() + 86400 * $add_date * 7;
                break;
            case '月':
                $expired_at = time() + 86400 * $add_date * 30;
                break;
        }

        //  radcheck 到期时间
        $radcheck_value = date("d M Y H:i:s ",$expired_at);

        $money = $price / $batch_add_num;

        foreach($username as $value)
        {
            //   Radcheck 插入用户数据
            $where = [];
            $where['username'] =$value;
            $where['value'] =$password;
            $where['attribute'] ='Cleartext-Password';
            $where['op'] =':=';

            $account_id = Radcheck::insertGetId($where);


            $arr = [];
            $arr['username'] =$value;
            $arr['attribute'] ='Expiration';
            $arr['op'] =':=';
            $arr['value'] = $radcheck_value;

            Radcheck::insertGetId($arr);



            //  添加用户数据
            $account = [];

            $account['manage_id'] = $manage_id;
            $account['user_id'] = $account_id;
            $account['username'] = $value;
            $account['password'] = $password;
            $account['terrace_id'] = 5;             //  平台标识  5 代理平台
            $account['con_max'] =$connect_num ;
            $account['created_at'] = date('Y-m-d H:i:s',time());
            $account['updated_at'] = date('Y-m-d H:i:s',time());
            $account['expired_at'] = date('Y-m-d H:i:s',$expired_at);
            $account['account_type'] = '付费';
            $account['vip'] = 1;
            $account['set_meal_type'] = $set_meal_type;
//            $account['remark'] = $remark;
            $ret = Rad_users::insertGetId($account);

            $group = Radgroupcheck::where('value',$connect_num)->get()->toArray();

//        // 为空  则添加组
            if(empty($group))
            {
                //   添加组
                $group_parm = [];
                $group_parm['groupname'] = 'c'.$connect_num;
                $group_parm['attribute'] = 'Simultaneous-Use';
                $group_parm['op'] = ':=';
                $group_parm['value'] = $connect_num;
                Radgroupcheck::insertGetId($group_parm);
                //   添加组的属性

                //  属性1
                $group_attribute1= [];
                $group_attribute1['groupname'] = 'c'.$connect_num;
                $group_attribute1['attribute'] = 'Auth-Type';
                $group_attribute1['op'] = ':=';
                $group_attribute1['value'] = 'Local';


                //  属性2
                $group_attribute2= [];
                $group_attribute2['groupname'] = 'c'.$connect_num;
                $group_attribute2['attribute'] = 'Service-Type';
                $group_attribute2['op'] = ':=';
                $group_attribute2['value'] = 'Framed-User';


                //  属性3
                $group_attribute3= [];
                $group_attribute3['groupname'] = 'c'.$connect_num;
                $group_attribute3['attribute'] = 'Framed-IP-Address';
                $group_attribute3['op'] = ':=';
                $group_attribute3['value'] = '255.255.255.255';

                $group_attribute4= [];
                $group_attribute4['groupname'] = 'c'.$connect_num;
                $group_attribute4['attribute'] = 'Framed-IP-Netmask';
                $group_attribute4['op'] = ':=';
                $group_attribute4['value'] = '255.255.255.0';

                Radgroupreply::insertGetId($group_attribute1);
                Radgroupreply::insertGetId($group_attribute2);
                Radgroupreply::insertGetId($group_attribute3);
                Radgroupreply::insertGetId($group_attribute4);
            }

            //   添加用户与组的对应关系
            $user_group = [];
            $user_group['username'] = $value;
            $user_group['groupname'] = 'c'.$connect_num;
            $user_group['priority'] = 1;
            Radusergroup::insertGetId($user_group);


            // 添加限速表
            $radreply = Radreply::where('username',$value)->get()->toArray();

            if(empty($radreply))
            {
                $param['username'] = $value;
                $param['attribute'] = 'Mikrotik-Rate-Limit';
                $param['op'] = '=';
                switch($set_meal_type)
                {
                    case 1: $param['value'] = '512k/512k';break;
                    case 2:  $param['value'] = '2048k/2048k';break;
                    case 3: $param['value'] = '4096k/4096k';break;
                }

                $id = Radreply::insertGetId($param);
            }

            $rad = Rad_manage::find($manage_id);

            //   订单信息

            $oder = [];

            $order['balance'] = $rad->balance - $money;
            $order['date'] =$add_date;
            $order['price'] =$money;
            $order['account_type'] = '付费';
            $order['connect_num'] =$connect_num;
            $order['user_id'] = $manage_id;                 //   用户id

            $order['to_user'] =$account_id;
            $order['order_no'] =self::createUuid();
            $order['pay_channel'] =2;                    //    支付标识   余额  2

            $order['created_at'] = date('Y-m-d H:i:s',time());
            $order['updated_at'] = date('Y-m-d H:i:s',time());


            $id = Rad_order::insertGetId($order);

            if($id)
            {
                $orders = Rad_order::find($id);
                $orders->status = 1;
                $orders->save();
            }

            $rad->balance = $rad->balance-$money;
            $rad->save();
        }

        return self::ShowMessage();

    }
    
    
    
    
    
    
    
    
    //可以指定前缀   生成用户ID
    static function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8) . '-';
        $uuid .= substr($str,8,4) . '-';
        $uuid .= substr($str,12,4) . '-';
        $uuid .= substr($str,16,4) . '-';
        $uuid .= substr($str,20,12);
        return $prefix . $uuid;
    }




    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }



}















